package com.shwread.android.qysw.activity.pay;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.NewActionHelp;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.shwread.android.qysw.activity.BaseSimpleActivity;
import com.shwread.android.qysw.bean.PartyFeeDetail;
import com.shwread.android.qysw.visitMap.ToastUtil;
import com.shwread.android.qysw10000229.R;
import com.shwread.http.base.ObjectHttpResponseHandler;

import org.apache.http.Header;

import java.lang.reflect.Type;
import java.text.DecimalFormat;

import logic.pay.PayResult;
import logic.pay.PayUtil;

/**
 * Created by lexy on 2016/12/9.
 * 缴纳党费 该页面分为已缴纳和未缴纳两种情况
 */
public class PartyFeePayActivity extends BaseSimpleActivity {

    //标题
    private Button btnBack;
    private TextView tvTitle;

    //已经缴纳过
    private TextView tvFeeTotalPayed, tvFeePayStatuPayed, tvFeeNotePayed, tvPartyFeePayedMonth,
            tvPartyFeePayedMore, tvPartyFeePayedTotal, tvPartyFeePayedDate;

    //未缴纳过
    private TextView tvFeePayStatuNoPay, tvFeeTotalNoPay, tvFeeNoteNoPay, tvFeeNoPayMonth;
    private EditText etNoPayMoreFee;
    private Button tVConfirmNoPayPartyFee;

    private int orderId = -1;
    private int statu = -1;
    private DecimalFormat decimalFormat = null;
    private char symbol = '￥';
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case PayUtil.SDK_PAY_FLAG: {
                    PayResult payResult = new PayResult((String) msg.obj);

                    // 支付宝返回此次支付结果及加签，建议对支付宝签名信息拿签约时支付宝提供的公钥做验签
                    String resultInfo = payResult.getResult();

                    String resultStatus = payResult.getResultStatus();

                    // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
                    if (TextUtils.equals(resultStatus, "9000")) {
                        tVConfirmNoPayPartyFee.setClickable(true);
//												Toast.makeText(context, "支付成功", Toast.LENGTH_SHORT).show();
                        Intent intent = new Intent(PartyFeePayActivity.this, PartyFeePaySuccessActivity.class);
                        intent.putExtra("statu", 2);
                        intent.putExtra("orderId", orderId);
                        startActivity(intent);
                        finish();
                    } else {
                        tVConfirmNoPayPartyFee.setClickable(true);
                        // 判断resultStatus 为非“9000”则代表可能支付失败
                        // “8000”代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
                        if (TextUtils.equals(resultStatus, "8000")) {
                            Toast.makeText(PartyFeePayActivity.this, "支付结果确认中", Toast.LENGTH_SHORT).show();

                        } else {
                            // 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
                            Toast.makeText(PartyFeePayActivity.this, "支付失败", Toast.LENGTH_SHORT).show();

                        }
                    }
                    break;
                }
                case PayUtil.SDK_CHECK_FLAG: {
                    tVConfirmNoPayPartyFee.setClickable(true);
                    Toast.makeText(PartyFeePayActivity.this, "是否有支付宝认证账号：" + msg.obj, Toast.LENGTH_SHORT).show();
                    break;
                }
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //根据传过来的状态判断当前显示什么view，
        decimalFormat = new DecimalFormat("0.00");
        statu = getIntent().getIntExtra("statu", -1);
        orderId = getIntent().getIntExtra("orderId", -1);
        if (statu == 1) {
            setContentView(R.layout.activity_party_fee_pay);
            initNoPayView();
        } else {
            setContentView(R.layout.activity_party_fee_payed);
            initPayedView();
        }

        btnBack = (Button) findViewById(R.id.common_header_back);
        btnBack.setVisibility(View.VISIBLE);
        tvTitle = (TextView) findViewById(R.id.common_header_name);
        tvTitle.setText("党费缴纳");
        btnBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PartyFeePayActivity.this.finish();
            }
        });
        NewActionHelp.getPartyFeeOrderInfo(this, orderId, new GetPartyFeeOrderInfoHandler());
    }

    void initPayedView() {
        tvFeeTotalPayed = (TextView) findViewById(R.id.tvFeeTotalPayed);
        tvFeePayStatuPayed = (TextView) findViewById(R.id.tvFeePayStatuPayed);
        tvFeeNotePayed = (TextView) findViewById(R.id.tvFeeNotePayed);
        tvPartyFeePayedMonth = (TextView) findViewById(R.id.tvPartyFeePayedMonth);
        tvPartyFeePayedMore = (TextView) findViewById(R.id.tvPartyFeePayedMore);
        tvPartyFeePayedTotal = (TextView) findViewById(R.id.tvPartyFeePayedTotal);
        tvPartyFeePayedDate = (TextView) findViewById(R.id.tvPartyFeePayedDate);
    }

    void initNoPayView() {
        tvFeePayStatuNoPay = (TextView) findViewById(R.id.tvFeePayStatuNoPay);
        tvFeeTotalNoPay = (TextView) findViewById(R.id.tvFeeTotalNoPay);
        tvFeeNoteNoPay = (TextView) findViewById(R.id.tvFeeNoteNoPay);
        tvFeeNoPayMonth = (TextView) findViewById(R.id.tvFeeNoPayMonth);
        etNoPayMoreFee = (EditText) findViewById(R.id.etNoPayMoreFee);
        tVConfirmNoPayPartyFee = (Button) findViewById(R.id.tVConfirmNoPayPartyFee);
    }

    class GetPartyFeeOrderInfoHandler extends ObjectHttpResponseHandler<PartyFeeDetail> {

        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            Log.e("党费订单详情---Failure", responseString);
        }

        @Override
        public void onSuccess(int statusCode, Header[] headers, PartyFeeDetail partyFeeDetail, String responseString) {
            Log.e("党费订单详情---Success", responseString);
            if (statu == 1) {//未交
                tvFeeTotalNoPay.setText(String.valueOf(symbol) + decimalFormat.format(partyFeeDetail.getPartyFees() / 100));
                tvFeeNoteNoPay.setText("费用金额说明：" + partyFeeDetail.getFeesExplain());
                tvFeeNoPayMonth.setText(partyFeeDetail.getPartyfeesMonth());
                tVConfirmNoPayPartyFee.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        tVConfirmNoPayPartyFee.setClickable(false);
                        float extraFee = 0;
                        String extraStr = "";
                        String extraFeeStr = etNoPayMoreFee.getText().toString();
                        if (!TextUtils.isEmpty(extraFeeStr)) {
                            if (extraFeeStr.matches("^\\+{0,1}[1-9]\\d*") || extraFeeStr.matches("\\+{0,1}[0]\\.[1-9]\\d?|\\+{0,1}[0]\\.[0][1-9]|\\+{0,1}[1-9]\\d*\\.\\d*")) {
                                extraFee = Float.parseFloat(etNoPayMoreFee.getText().toString());
                                DecimalFormat decimalFormat = new DecimalFormat("0");
                                extraStr = decimalFormat.format(extraFee * 100);
                                NewActionHelp.createPartyFeeOrder(PartyFeePayActivity.this, orderId, extraStr, new CreatePartyFeeOrderHandler());
                            } else {
                                tVConfirmNoPayPartyFee.setClickable(true);
                                ToastUtil.show(PartyFeePayActivity.this, "请输入正确的金额");
                                return;
                            }
                        } else {
                            NewActionHelp.createPartyFeeOrder(PartyFeePayActivity.this, orderId, "0", new CreatePartyFeeOrderHandler());
                        }
                    }
                });
            } else {
                tvFeeTotalPayed.setText(String.valueOf(symbol) + decimalFormat.format(partyFeeDetail.getActualPartyFees() / 100));
                tvFeeNotePayed.setText("费用金额说明：" + partyFeeDetail.getFeesExplain());
                tvPartyFeePayedMonth.setText(partyFeeDetail.getPartyfeesMonth());
                tvPartyFeePayedMore.setText(decimalFormat.format(partyFeeDetail.getExtraFee() / 100) + "元");
                tvPartyFeePayedTotal.setText(decimalFormat.format(partyFeeDetail.getActualPartyFees() / 100) + "元");
                tvPartyFeePayedDate.setText(partyFeeDetail.getPayTime());
            }
        }

        @Override
        public Type getType() {
            return new TypeToken<PartyFeeDetail>() {
            }.getType();
        }
    }

    class CreatePartyFeeOrderHandler extends ObjectHttpResponseHandler<PartyFeeDetail> {

        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            Log.e("党费下订单---Failure", responseString);
            tVConfirmNoPayPartyFee.setClickable(true);
        }

        @Override
        public void onSuccess(int statusCode, Header[] headers, PartyFeeDetail partyFeeDetail, String responseString) {
            Log.e("党费下订单---Success", responseString);
            final String orderInfo = PayUtil.getOrderInfo(partyFeeDetail.getOrderNo(), "党费缴纳", "党费缴纳", String.valueOf(partyFeeDetail.getActualPartyFees() / 100));
            PayUtil.pay(PartyFeePayActivity.this, handler, orderInfo);
        }

        @Override
        public Type getType() {
            return new TypeToken<PartyFeeDetail>() {
            }.getType();
        }
    }
}
